#ifndef U_SERVICE_H
#define U_SERVICE_H

#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
using boost::asio::ip::udp;

#include "i_package_receiver.h"
#include "i_package_sender.h"

class UdpService : public boost::enable_shared_from_this<UdpService>, public IPackageSender
{
	static const int MaxPackageSize;

	udp::socket socket_;
	udp::endpoint currentRemoteAddr_;
	boost::asio::streambuf recvBuf_;
	boost::shared_ptr<IPackageReceiver> packageHandler_;

	void scheduleReceive();
	void handleReceive(const boost::system::error_code& error,
		std::size_t byteTransferred);

	UdpService(unsigned short port, boost::asio::io_service& ioService);
public:
	typedef boost::shared_ptr<UdpService> Ptr;
	
	static Ptr newInstance(unsigned short port, boost::asio::io_service& ioService);

	void start();

	void setPackageHandler(boost::shared_ptr<IPackageReceiver> packageHandler);
	virtual void send(const udp::endpoint& addr, boost::asio::const_buffers_1& package);
	virtual void send(const udp::endpoint& addr, IPackage::Ptr package, unsigned int seq);
	virtual boost::asio::io_service& ioService();
};


#endif